package org.jeecg.common.multipart;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FtcspRestUtils {
    private static final Logger log = LoggerFactory.getLogger(FtcspRestUtils.class);

    public static String resolveURL(String url, boolean external) {
        url = url.substring("http://".length());
        String[] urlParts = url.split("/");
        int gatewayIndex = -1;
        int serviceIndex;
        if (external) {
            gatewayIndex = 1;
            serviceIndex = 2;
        } else if (!urlParts[0].equals("gateway") && !urlParts[0].equals("foresee-gateway-server")) {
            serviceIndex = 0;
        } else {
            gatewayIndex = 0;
            serviceIndex = 1;
        }

        String serviceNameEnv;
        if (gatewayIndex >= 0) {
            serviceNameEnv = getEnv("FTCSP_ENV_" + urlParts[gatewayIndex]);
            if (StrUtil.isNotBlank(serviceNameEnv)) {
                urlParts[gatewayIndex] = serviceNameEnv;
            }
        }

        serviceNameEnv = getEnv("FTCSP_ENV_" + urlParts[serviceIndex]);
        if (StrUtil.isNotBlank(serviceNameEnv)) {
            urlParts[serviceIndex] = serviceNameEnv;
        }

        CoreContext.setServerName(urlParts[serviceIndex]);
        StringBuffer sb = new StringBuffer("http:/");
        String[] var7 = urlParts;
        int var8 = urlParts.length;

        for (int var9 = 0; var9 < var8; ++var9) {
            String part = var7[var9];
            sb.append("/").append(part);
        }

        String newUrl = sb.toString();
        if (!url.equals(newUrl)) {
            log.debug("Resolve url [{}] to [{}].", url, newUrl);
        }

        return newUrl;
    }

    private static String getEnv(String name) {
        name = name.replace('-', '_');
        String value = System.getProperty(name);
        if (StrUtil.isBlank(value)) {
            value = System.getenv(name);
        }

        return value;
    }
}
